<?php

// 公共助手函数

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($data, $domain = false)
    {
        // $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        // $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        // if ($domain && !preg_match($regex, $url)) {
        //     $domain = is_bool($domain) ? request()->domain() : $domain;
        //     $url = $domain . $url;
        // }
        // return $url;

        if (is_array($data) || is_object($data)) {
            foreach ($data as $key => &$value) {
                $value = cdnurl($value, $domain);
            }
            return $data;
        }

        if (!$domain) {
            $config = \think\Config::get('site.cdnurl');
            $domain = $config ? $config : request()->domain();
        }

        if (preg_match('/^https?.*?/', $data)) {
            $parse = parse_url($data);
            $domainparse = parse_url($domain);
            if(isset($parse['host']) && isset($domainparse['host']) && $parse['host'] == request()->host()  &&  $parse['host'] != $domainparse['host']){
               $data = $domain.$parse['path'];
            }
            return  $data;
        }
        
        return $domain . $data;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param    string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach ($iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var    数组
     * @param string $indent 缩进字符
     * @return string
     */
    function var_export_short($var, $indent = "")
    {
        switch (gettype($var)) {
            case "string":
                return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
            case "array":
                $indexed = array_keys($var) === range(0, count($var) - 1);
                $r = [];
                foreach ($var as $key => $value) {
                    $r[] = "$indent    "
                        . ($indexed ? "" : var_export_short($key) . " => ")
                        . var_export_short($value, "$indent    ");
                }
                return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
            case "boolean":
                return $var ? "TRUE" : "FALSE";
            default:
                return var_export($var, true);
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}


/**
 * 富文本转化全路径
 */
function richTextAbsoluteUrl($html_content, $domain = null)
{
    if (is_null($domain)) {
        $config = \think\Config::get('site.cdnurl');
        $domain = $config ? $config : request()->domain();
    }
    if (preg_match_all("/(<video[^>]+src=\"([^\"]+)\"[^>]*>)|(<img[^>]+src=\"([^\"]+)\"[^>]*>)|(<a[^>]+href=\"([^\"]+)\"[^>]*>)|(<img[^>]+src='([^']+)'[^>]*>)|(<a[^>]+href='([^']+)'[^>]*>)/i", $html_content, $regs)) {
        foreach ($regs[0] as $num => $url) {
            $html_content = str_replace($url, reUrl2AbUrl($url, $domain), $html_content);
        }
    }
    return $html_content;
}


/**方法*/
function reUrl2AbUrl($l1, $l2)
{
    if (preg_match("/(.*)(href|src)\=(.+?)( |\/\>|\>).*/i", $l1, $regs)) {
        $I2 = $regs[3];
    }
    if (strlen($I2) > 0) {
        $I1 = str_replace(chr(34), "", $I2);
        $I1 = str_replace(chr(39), "", $I1);
    } else {
        return $l1;
    }
    $url_parsed = parse_url($l2);
    $scheme = isset($url_parsed['scheme']) ? $url_parsed["scheme"] : '';
    if ($scheme != "") {
        $scheme = $scheme . "://";
    }
    $host = isset($url_parsed["host"]) ? $url_parsed['host'] : '';
    $l3 = $scheme . $host;
    if (strlen($l3) == 0) {
        return $l1;
    }
    $path = isset($url_parsed["path"]) ? dirname($url_parsed["path"]) : '';
    if (!empty($path)) {
        if ($path[0] == "\\") {
            $path = "";
        }
    }
    $pos = strpos($I1, "#");
    if ($pos > 0)
        $I1 = substr($I1, 0, $pos);

    //判断类型
    if (preg_match("/^(http|https|ftp):(\/\/|\\\\)(([\w\/\\\+\-~`@:%])+\.)+([\w\/\\\.\=\?\+\-~`@\':!%#]|(&amp;)|&)+/i", $I1)) {
        return $l1;
    } //http开头的url类型要跳过
    elseif ($I1[0] == "/") {
        $I1 = $l3 . $I1;
    } //绝对路径
    elseif (substr($I1, 0, 3) == "../") { //相对路径
        while (substr($I1, 0, 3) == "../") {
            $I1 = substr($I1, strlen($I1) - (strlen($I1) - 3), strlen($I1) - 3);
            if (strlen($path) > 0) {
                $path = dirname($path);
            }
        }
        $I1 = $l3 . $path . "/" . $I1;
    } elseif (substr($I1, 0, 2) == "./") {
        $I1 = $l3 . $path . substr($I1, strlen($I1) - (strlen($I1) - 1), strlen($I1) - 1);
    } elseif (strtolower(substr($I1, 0, 7)) == "mailto:" || strtolower(substr($I1, 0, 11)) == "javascript:") {
        return $l1;
    } else {
        $I1 = $l3 . $path . "/" . $I1;
    }
    return str_replace($I2, "\"$I1\"", $l1);
}

/**
 *  富文本绝对路径替换成相对路径
 * @param $html_content
 * @param $host
 * @return mixed
 */
function richTextRelativeUrl($html_content, $domain = null)
{
    if (is_null($domain)) {
        $config = \think\Config::get('site.cdn_url');
        $domain = $config ? $config : request()->domain();
    }

    return str_replace($domain, '', $html_content);
}



/**
* 记录自定义日志
* @param msg 日志内容，支持array和object
* @param file 文件夹
*/ 
function doLog($msg = NULL,$file = "defined")
{
    if($msg)
    { 
		$config = [
			'type'  =>  'File',
			'path'  =>  LOG_PATH.$file.DS
		];

		try{

			if( !is_dir( $config['path'] ) )
			{
				mkdir($config['path']);
			}

			$Log = new \think\Log;
			$Log->init($config);
			$msg = is_string($msg) ? $msg :json_encode( $msg, JSON_UNESCAPED_UNICODE);
			$Log->write($msg."\r\n","LOG");

		}catch(\Exception $e)
		{

		}
    }
}


/**
* curl 请求
* @param postFields array 如果不空的话将使用post方法请求
*/ 
function fhcurl( $url = null, $postFields = null, $header = [] ) {
    if( empty($url) )
    {
        return "";
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $postBodyString = "";
    if (is_array($postFields) && 0 < count($postFields)) {

        foreach ($postFields as $k => $v) { 
            $postBodyString .= "$k=" . urlencode($v) . "&";
        }
        unset ($k, $v);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
    }elseif($postFields && is_string($postFields)){
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }

    $default_header = ['content-type: application/x-www-form-urlencoded;charset=utf-8'];
    $headers = empty( $header ) ? $default_header : array_merge( $default_header, $header );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $reponse = curl_exec($ch);

    if (curl_errno($ch)) {

        throw new Exception(curl_error($ch), 0);
    } else {
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (200 !== $httpStatusCode) {
            throw new Exception($reponse, $httpStatusCode);
        }
    }

    curl_close($ch);
    return $reponse;
}



/**
* 指定字符串脱敏,只支持utf-8
* @param $str string
* @param $start int
* @param $len int
* @param $replace int
*/
function remove_sens( $str = NULL ,$start = 0,$len = 1, $replace = "*" )
{
	$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
    
	if( empty( trim( $str ) ) )
        return "";

    $slen = $mbLen = mb_strlen($str);
    // $slen = strlen($str);
	$strlen = $mbLen == $slen ? $slen : $mbLen;

	if( $len > $strlen )
	{
		$len = $strlen;
	}

	$stars = "";
	for ($i=0; $i < $len; $i++) { 
		$stars .= $replace;
	}

    $left_str = ( 0 < $start ) ? mb_substr( $str, 0, $start ) : "";

    if( $strlen < $start+$len ){
        $right_str = "";
    }else{
        $right_str = mb_substr( $str, $start+$len-$strlen );
    }
	return $left_str.$stars.$right_str;
}
